import React, { ReactElement, useState, useEffect } from 'react'
import { AuthoritySchema } from '@src/components/schema/authority'
import { RoleShcema } from '@src/components/schema/role'
import { awaitWrap } from '@src/assets/js/tool'
import { getAuthority } from './ajax'
import style from './index.module.less'
import AuthorityTree from './components/authorityTree'

async function initAuthorityList (setAuthorityList: (v: AuthoritySchema[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getAuthority())
  if (e === null && d instanceof Array) {
    d.sort((a, b) => a.orderno - b.orderno)
    setAuthorityList(d)
  }
}

interface Props {
  currentRole: RoleShcema | null
  onChange: (v: string[]) => void
}

function Main ({ currentRole, onChange }: Props): ReactElement {
  const [authorityList, setAuthorityList] = useState<AuthoritySchema[]>([])
  const [currentAuthority, setCurrentAuthority] = useState<string[]>([])
  useEffect(() => {
    initAuthorityList(setAuthorityList).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    if (currentRole !== null) {
      if (currentRole.rules instanceof Array) {
        setCurrentAuthority(currentRole.rules)
      } else {
        setCurrentAuthority([])
      }
    }
  }, [currentRole])
  return (
    <div className={style.container}>
      <AuthorityTree value={currentAuthority} tree={authorityList} onChange={d => onChange(d)} />
    </div>
  )
}

export default Main
